import React, { useRef, useEffect } from 'react'
import { useStore } from 'react-redux'
import * as echarts from 'echarts';
import { Row, Col, Card } from 'antd'
import http from '../../api'

export default function Home() {
  const pieChartRef = useRef(null)
  const { UserInfo } = useStore().getState()

  useEffect(() => {
    getPubInfo()
  }, [])

  const getPubInfo = async () => {
    const classRes = await http.get('/categories')
    const newRes = await http.get(`/news?author=${UserInfo.username}`)
    const xData = classRes.data.map(item => item.title)
    const yData = newRes.data.map(item => item.view)
    renderPieChart(xData, yData)
  }


  const renderPieChart = (xData, yData) => {
    var chartDom = pieChartRef.current
    var myChart = echarts.init(chartDom);
    var option;

    option = {
      title: {
        text: '新闻分类浏览量',
        left: "center"
      },
      // 柱状图鼠标上浮提示框
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      xAxis: {
        type: 'category',
        data: xData,
        name: '分类'
      },
      yAxis: {
        name: '浏览量',
        type: 'value'
      },
      series: [
        {
          data: yData,
          type: 'bar'
        }
      ]
    }
    option && myChart.setOption(option);
    window.onresize = () => {
      myChart.resize()
    }
  }
  return (
    <div>
      <h1>home</h1>
      <Row>
        <Col span={6}>
          <Card title="Card title" bordered={false} style={{ width: 300 }}>
            <p>Card content</p>
            <p>Card content</p>
            <p>Card content</p>
          </Card>
        </Col>
        <Col span={12}>
          <div id='pieChart' ref={pieChartRef} style={{ width: '100%', height: '300px' }}></div>
        </Col>
        <Col span={6}>
          <Card title="Card title" bordered={false} style={{ width: 300 }}>
            <p>Card content</p>
            <p>Card content</p>
            <p>Card content</p>
          </Card>
        </Col>
      </Row>
    </div>
  )
}
